package com.yswy.common.utils.sms;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yswy.common.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 加密相关
 *
 * @author huqiankun
 * @date 2019/12/12 17:50
 */
@Slf4j
@Service
public class CnyzSmsUtil {

    private static final String CHARSET = "utf-8";

    private static final String DESEDE = "DESede";

    private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
    private static final String SORCERANMDOM = "SHA1PRNG";



    @Value(value = "${SMS.CNYZ.account}")
    private String account ;
    @Value(value = "${SMS.CNYZ.pass}")
    private String pass ;
    @Value(value = "${SMS.CNYZ.url}")
    private String url ;

    @Value(value = "${SMS.CNYZ.accountyx}")
    private String accountyx ;
    @Value(value = "${SMS.CNYZ.passyx}")
    private String passyx ;
    @Value(value = "${SMS.CNYZ.urlyx}")
    private String urlyx ;


    //通知短信
//    private static final String account = "YZM8130641";
//    private static final String pass = "C03oMnCUIu3875";
//    private static final String url = "http://smssh1.253.com/msg/v1/send/json";

//    YZM8944238
//    6u08U3vK6B6359

    //会员营销短信
//    private static final String urlyx = "https://smssh1.253.com/msg/send/encrypt/json";
//    private static final String accountyx = "M0664706";
//    private static final String passyx = "66HNMcW6bV2e02";




    /**
     * 使用指定字符串生成3DES加密密钥
     * @param key
     * @return
     */
    private static SecretKeySpec getPwd(String key) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(DESEDE);
        SecureRandom random = SecureRandom.getInstance(SORCERANMDOM);
        random.setSeed(key.getBytes());
        kg.init(random);
        //生成一个密钥
        SecretKey secretKey = kg.generateKey();
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), DESEDE);
        return secretKeySpec;
    }
    /**
     * 加密
     *
     * @param content 加密内容
     * @param key     加密key
     * @return 密文
     */
    public static String encrypt(String content, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        // 创建密码器
        byte[] byteContent = content.getBytes(CHARSET);
        cipher.init(Cipher.ENCRYPT_MODE, getPwd(key));
        // 初始化为加密模式的密码器
        byte[] result = cipher.doFinal(byteContent);
        return Base64.encodeBase64String(result);
    }
    /**
     * 解密
     *
     * @param content 解密内容
     * @param key     解密key
     * @return 明文
     */
    public static String decrypt(String content, String key) throws Exception {
        // 实例化
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 使用密钥初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, getPwd(key)); // 执行操作
        byte[] result = cipher.doFinal(Base64.decodeBase64(content));
        String resultStr = new String(result, CHARSET);
        return resultStr;
    }

    public static void main(String[] args) {
//        sendHsx("18080455214", "123456");
//        sendHxsDownloadUrl("18080455214", "您已支付成功，下载app查收话费券包，如需下载及售后点击：https://s.r.sn.cn/Z376ep " ,"惠省星" );
    }
//    public static void test(String phone,  String  code){
//        try {
//            JSONObject json = new JSONObject();
//            json.put("account",account);
//            json.put("password",pass);
//            json.put("msg","【惠省星】您的验证码为："+code+"，该验证码5分钟内有效，请勿泄漏他人。");
//            json.put("phone",phone);
//            System.out.println(json.toJSONString());
//            sendSms( json);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }


    public void sendCode(String phone,  String  code ,  String title){
        try {
            JSONObject json = new JSONObject();
            json.put("account",account);
            json.put("password",pass);
            json.put("msg","【"+title+"】您的验证码为："+code+"，该验证码5分钟内有效，请勿泄漏他人。");
            json.put("phone",phone);
            sendSms( json, url);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void sendHsx(String phone,  String  code){
        try {
            JSONObject json = new JSONObject();
            json.put("account",account);
            json.put("password",pass);
            json.put("msg","【惠省星】您的验证码为："+code+"，该验证码5分钟内有效，请勿泄漏他人。");
            json.put("phone",phone);
            sendSms( json, url);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void sendXxb(String phone,  String  code){
        try {
            JSONObject json = new JSONObject();
            json.put("account",account);
            json.put("password",pass);
            json.put("msg","【星选宝】您的验证码为："+code+"，该验证码5分钟内有效，请勿泄漏他人。");
            json.put("phone",phone);
            sendSms( json , url);
        }
        catch (Exception  e){
            e.printStackTrace();
        }
    }


    public void sendHxsDownloadUrl(String phone,  String  msg , String appName){
        try {
            JSONObject json = new JSONObject();
            json.put("account",accountyx);
            json.put("password",passyx);
            json.put("msg","【"+appName+"】"+msg);
            json.put("phone",phone);
            log.info(json.toJSONString());
            sendSms( json , url);
        }
        catch (Exception  e){
            e.printStackTrace();
        }
    }



    public static void sendSms(JSONObject json , String url){
        Map<String, String> userMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : json.entrySet()) {

            userMap.put(entry.getKey(), entry.getValue().toString());
        }
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type" ,  "application/json;charset=UTF-8");
        //HttpUtil.doPost(url ,json);
//        String s = HttpUtil.post(url ,userMap , headMap);
//        System.out.println(s);
        try {
            HttpUtil.sendHttpPost(url ,json.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private static String trimToString(Object obj){
        if (obj==null){
            return StringUtils.EMPTY;
        }
        String str = obj.toString();
        if (StringUtils.isNotBlank(str) && !str.toLowerCase().equals("null")){
            return str;
        }else {
            return StringUtils.EMPTY;
        }
    }


}